package managedbean;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;

import jpa.PetJPA;
import jpa.ShoppingCart;
import jpa.StatusJPA;
import ejb.CatalogFacadeRemote;

/**
 * Managed Bean RemovePetFromShoppingCartMBean
 */
@ManagedBean(name = "removePet")
@SessionScoped
public class RemovePetFromShoppingCartMBean {
	private static final long serialVersionUID = 1L;

	@EJB
	private CatalogFacadeRemote removePetFromCartRemote;
	
	public String removePetFromShoppingCart() throws Exception
	{	
		FacesContext fc = FacesContext.getCurrentInstance();
		Map<String,String> params = fc.getExternalContext().getRequestParameterMap();
		String id = params.get("idPet");
		ShoppingCart cart = (ShoppingCart)fc.getExternalContext().getSessionMap().get("shoppingCart");
		List<PetJPA> pets = cart.getPets();
		for(PetJPA pet : pets) {
			if(pet.getId() == Integer.parseInt(id)) {
				pets.remove(pet);
				/**
				 * Una vez eliminado el animal, cambiamos su estado a Available
				 * 
				 */
				StatusJPA statusToChange = new StatusJPA("Available");
				modifyStatusPet(pet,statusToChange);
				break;
			}
		}
		
		return "showShoppingCartView";
	}

	/**
	 * Method to change status	
	 */
	public void modifyStatusPet(PetJPA pet,StatusJPA statusToChange) throws Exception{
		Properties props = System.getProperties();
		Context ctx = new InitialContext(props);
		removePetFromCartRemote = (CatalogFacadeRemote) ctx.lookup("java:app/PracticalCaseStudyJEE.jar/CatalogFacadeBean!ejb.CatalogFacadeRemote");
		removePetFromCartRemote.modifyStatusPet(pet, statusToChange);
	}

}
